// 提供响应式变量：录音状态，录音总时间，
// 提供控制的嫁接
import { useRef, useState, useEffect, useCallback } from 'react';
import { message } from 'antd';
import events from '@/utils/eventBus';
import WEBSOCKET_TYPES from '@/pages/Recruitment/Interview/utils/WEBSOCKET_TYPES';
import EVENTBUS_TYPES from '@/pages/Recruitment/Interview/utils/EVENTBUS_TYPES';
import WARNING_TYPES from '@/pages/Recruitment/Interview/utils/WARNING_TYPES';
import RealtimeUploader from '../utils/RealtimeUploader';

// 下面三个是配合无声报警用的
let lastZeroTime = 0;
let lastVol = 1; // 默认值必须 > 0，否则开始就无声的状态，不会提示无声。
let lastWarning = '';
/**
 * 重置数据,
 * 录音状态变化时调用
 */
const reset = () => {
    lastZeroTime = 0;
    lastVol = 1;
    lastWarning = '';
};

/**
 * 获取实时上传对应数据
 * @param {String} onLinePartLink 已上传部分的链接，适用于暂存后刷新页面重新进入
 * @param {Boolean} isLoading 依赖数据的加载状态，为false才会创建录音实例
 * @param {JSON} recordTimeInfo 线上部分录音的开始、停止时间戳
 * @returns {Number} recorderState   -1 未初始化, 0停止， 1录制中， 2暂停
 * @returns duration  播放时间 时:分:秒
 * @returns volume  音量
 * @returns realTimeRECRef  录音实例 startRecAndUpload 开始录音，stopRec 停止，pauseRec 暂停，resumeRec 暂停后恢复
 */

function useRealTimeUpload(
    onLinePartLink = '',
    ossFileName = '',
    ossKeyName,
    isLoading,
    uploadRecInfoFunc,
    recordTimeInfo
) {
    const [recorderState, setRecorderState] = useState(-1); // -1未初始化，0停止，1播放中，2暂停
    const [uploadState, setUploadState] = useState(false); // true 正在上传， false 上传完毕
    const [duration, setDuration] = useState('00:00:00');
    const durationMSRef = useRef(0);
    const lastFailState = useRef(false);
    const realTimeRECRef = useRef(null); // 实时上传工具的实例
    const isOnline = useRef(true); // 网络连接状态

    const handleDisconnect = useCallback(() => {
        if (!isOnline.current) {
            return; // 不在线就不执行
        }
        if (realTimeRECRef.current) {
            isOnline.current = false;
            realTimeRECRef.current.handleDisconnected();
            message.error('网络断开，请检查！', 6);
            events.emit(EVENTBUS_TYPES.SET_EXTEND, true);
        }
    }, []);

    const handleConnected = useCallback(() => {
        if (!isOnline.current) {
            isOnline.current = true;
        }
    }, []);

    useEffect(() => {
        if (!isLoading) {
            console.log('RealTimeUpload 创建录音实例, onLinePartLink:', onLinePartLink);
            // 创建录音实例
            realTimeRECRef.current = new RealtimeUploader(
                (duration1, ms) => {
                    setDuration(duration1);
                    durationMSRef.current = ms;
                },
                vol => {
                    console.log('vol==>', vol);
                    if (vol === 0 && lastVol !== 0) {
                        // 从有声变到无声
                        lastZeroTime = Date.now(); // 记录时间
                        lastVol = 0;
                    } else if (vol === 0 && lastVol === 0) {
                        if (Date.now() - lastZeroTime > 60000) {
                            // 超过60秒无声则提示无声浪，便于测试缩减到10s
                            lastZeroTime = Date.now(); // 设置时间，等待下一个周期
                            lastWarning = WARNING_TYPES.WARNING;
                            events.emit(EVENTBUS_TYPES.SET_WARNING, WARNING_TYPES.WARNING); // 触发声音
                            events.emit(WEBSOCKET_TYPES.SEND_WARNING, WARNING_TYPES.WARNING); // 触发声音
                        }
                    } else if (lastVol === 0 && vol !== 0 && lastWarning === WARNING_TYPES.WARNING) {
                        lastWarning = WARNING_TYPES.NONE;
                        events.emit(EVENTBUS_TYPES.SET_WARNING, WARNING_TYPES.NONE); // 触发声音
                        events.emit(WEBSOCKET_TYPES.SEND_WARNING, WARNING_TYPES.NONE); // 触发声音
                    } else {
                        // 声音不为0
                        lastVol = vol;
                    }
                },
                state => {
                    // 录音状态变化
                    console.log('setRecorderState:', state);
                    setRecorderState(state);
                    events.emit(WEBSOCKET_TYPES.SET_REC_STATE, state);
                    reset();
                },
                state => {
                    setUploadState(state);
                },
                isFail => {
                    // 上传连续失败3次的回调
                    if (isFail) {
                        events.emit(EVENTBUS_TYPES.SET_WARNING, WARNING_TYPES.UPLOAD_FAIL);
                        lastFailState.current = isFail;
                    } else if (lastFailState.current) {
                        events.emit(EVENTBUS_TYPES.SET_WARNING, WARNING_TYPES.NONE);
                        lastFailState.current = false;
                    }
                },
                onLinePartLink,
                5000,
                ossFileName,
                ossKeyName,
                uploadRecInfoFunc,
                recordTimeInfo ? JSON.parse(recordTimeInfo)?.endTime : 0
            );
            // 监听断网
            window.addEventListener('offline', handleDisconnect);
            // 监听网络恢复
            window.addEventListener('online', handleConnected);
            // 监听 websocket 断开
            events.addListener(EVENTBUS_TYPES.SOCKET_DISCONNECT, handleDisconnect);
            // 监听 websocket 连接
            events.addListener(EVENTBUS_TYPES.SOCKET_CONNECTED, handleConnected);
        } else {
            console.log('依赖数据加载中');
        }
        return () => {
            window.removeEventListener('offline', handleDisconnect);
            window.removeEventListener('online', handleConnected);
            events.removeListener(EVENTBUS_TYPES.SOCKET_DISCONNECT, handleDisconnect);
            events.removeListener(EVENTBUS_TYPES.SOCKET_CONNECTED, handleConnected);
            if (realTimeRECRef.current && realTimeRECRef.current.rec) {
                realTimeRECRef.current.rec.close();
                realTimeRECRef.current = null;
            }
        };
    }, [isLoading]);

    return [recorderState, duration, durationMSRef, realTimeRECRef, uploadState];
}

export default useRealTimeUpload;
